package com.gxa.community.customer.controller.classification.jms;

import com.gxa.community.customer.service.classification.impl.ClassificationServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.activemq.command.ActiveMQObjectMessage;
import org.apache.activemq.command.ActiveMQTextMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import java.io.Serializable;

@Slf4j
@Component
public class HotWordsCacheListener {

    public static final String HOTWORDS_CACHE_USED = "hotWordsCache_used";
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @JmsListener(destination = "DelHotWordsCache",containerFactory = "containerFactory")
    public synchronized void delHotWordsCache(Message message, Session session) throws JMSException {
        //synchronized 多线程状态下保证消息的可靠！！！！！
        //利用messageID防止重复消费
        //先获取当前消息的ID
        String jmsMessageID = message.getJMSMessageID();
        log.info("当前消息的ID:{}",jmsMessageID);
        //去redis中比对该条消息是否消费过
        HashOperations<String, Object, Object> opsForHash = redisTemplate.opsForHash();
        Object o = opsForHash.get(HOTWORDS_CACHE_USED, jmsMessageID);
        if (!StringUtils.isEmpty(o)){
            //说明该消息已经被消费过了
            log.info("该消息已经被消费过了！");
            message.acknowledge();
            return;
        }
        ActiveMQTextMessage activeMQTextMessage = (ActiveMQTextMessage) message;
        String messageObject = activeMQTextMessage.getText();
        log.info("消息队列带过来的消息内容：{}",messageObject);
        Boolean delSuccess = redisTemplate.delete(ClassificationServiceImpl.HOT_WORDS);
        //将没有消费过的消息ID放入redis中，表示此次已经消费了
        opsForHash.put(HOTWORDS_CACHE_USED,jmsMessageID,1);
        log.info("热词缓存删除结果：{}",delSuccess);
        message.acknowledge();
    }




}
